#!/bin/sh

############################################################
# File: MakeMD.sh
#
# 这个Shell脚本功能是将当前目录下的markdown文件转
# 化成Html文件与Pdf文件
# 
# ChangeLog:
# 2015-07-01 Hevake Lee     创建并实现基本功能
# 2015-07-03 Hevake Lee     添加在生成html的过程中插入css功能
#                           使html看起来更美观
# 2015-07-24 Hevake Lee     使用pandoc替代原来的markdown命令
############################################################

markdown_files=`find -name "*.md" -type f | xargs`
markdown_css_file="$HOME/.markdown.css"

make_html() {
    src_file=$1
    target_file=${src_file/.md/.html}

    if [ ! -e $target_file -o $target_file -ot $src_file ]; then
        src_basename=`basename $src_file`
        title=${src_basename/.md/}

        echo '<html><head>' > $target_file
        echo "<title>$title</title>" >> $target_file
        echo '<meta charset="utf-8"/>' >> $target_file

        if [ -e $markdown_css_file ]; then
            echo '<style type="text/css">' >> $target_file
            cat $markdown_css_file >> $target_file
            echo '</style>' >> $target_file
        fi

        echo '</head>' >> $target_file
        echo '<body>' >> $target_file
        pandoc -f markdown -t html $src_file >> $target_file
        echo '</body></html>' >> $target_file

        echo "Making HTML for $src_file"
    fi
}

make_pdf() {
    src_file=$1
    target_file=${src_file/.md/.pdf}
    if [ ! -e $target_file -o $target_file -ot $src_file ]; then
        pandoc -f markdown $src_file -o $target_file
        echo "Making HTML for $src_file"
    fi
}

for this_markdown_file in ${markdown_files[@]}; do
    make_html $this_markdown_file
    #make_pdf $this_markdown_file
done
